<template>
  <div>
    <b-table
      ref="table"
      bordered
      :columns="columns"
      :out-loading="loading"
      :disabled="disabled"
      :request="loadData"
      :del-func="delFunc"
      :scroll="{ x: 1300 }"
      :export-config="{use:true,select:'现场成本节超分析明细',all:'现场成本节超分析明细'}"
      :is-show-count-bar="false"
    >
      <template slot="prefix" slot-scope="ref" v-if="!disabled">
        <a-button type="primary" @click="openDialog()" :loading="loadingAdd">添加</a-button>
      </template>
      <template slot="suffix" slot-scope="ref">
        <a-button type="primary" @click="openDialog(downloadApi)" :loading="loadingAdd">标准模板下载</a-button>
        <ExcelImportButton v-if="!disabled" @handleSubmit="importFunc" />
      </template>
      <span slot="index" slot-scope="text, record, index">{{ index + 1 }}</span>
      <template
        v-for="col in ['begininNumbers','monthinNumbers','allinNumbers',
        'beginoutNumbers','monthoutNumbers','alloutNumbers',
        'monthstocNumbers','mcNumbers','rate','exTaxPrice',
        'inTaxPrice','exTaxAmount','inTaxAmount','remark']"
        :slot="col"
        slot-scope="text, record, index"
      >
        <div :key="col">
          <template v-if="!disabled">
            <BaseInputNumber
              class="requiredFormItem"
              v-if="col !== 'remark'"
              v-model="record[col]"
              :precision="2"
              @blur="save(record)"
            />
            <BaseInput v-if="col === 'remark'" v-model="record[col]" @blur="save(record)" />
          </template>
          <template v-else>
            {{ text }}
          </template>
        </div>
      </template>
    </b-table>
    <material-list-and-dir
      ref="detailDialog"
      @createList="createList"
    />
  </div>
</template>
<script>
import Api from '@/api/material/benefitAnalysis/fieldCostAnalysis'

export default {
  props: {
    disabled: {
      type: Boolean
    },
    id: {
      type: String
    }
  },
  data() {
    return {
      loading: false,
      loadingAdd: false,
      columns: [
        { title: '序号', width: 70, scopedSlots: { customRender: 'index' } },
        { title: '物资名称', width: 200, dataIndex: 'materialName' },
        { title: '物料编码', width: 130, dataIndex: 'materialCode' },
        { title: '单位', width: 80, dataIndex: 'unit' },
        { title: '期初累计进场数量', width: 150, dataIndex: 'begininNumbers', scopedSlots: { customRender: 'begininNumbers' } },
        { title: '当月进场数量', width: 150, dataIndex: 'monthinNumbers', scopedSlots: { customRender: 'monthinNumbers' } },
        { title: '累计总进场量', width: 150, dataIndex: 'allinNumbers', scopedSlots: { customRender: 'allinNumbers' } },
        { title: '期初累计消耗数量', width: 150, dataIndex: 'beginoutNumbers', scopedSlots: { customRender: 'beginoutNumbers' } },
        { title: '当月消耗数量', width: 150, dataIndex: 'monthoutNumbers', scopedSlots: { customRender: 'monthoutNumbers' } },
        { title: '累计消耗数量', width: 150, dataIndex: 'alloutNumbers', scopedSlots: { customRender: 'alloutNumbers' } },
        { title: '当月库存数量', width: 150, dataIndex: 'monthstocNumbers', scopedSlots: { customRender: 'monthstocNumbers' } },
        { title: '材料超欠供数量', width: 150, dataIndex: 'mcNumbers' },
        { title: '税率', width: 150, dataIndex: 'rate', scopedSlots: { customRender: 'rate' } },
        { title: '超欠供不含税单价', width: 150, dataIndex: 'exTaxPrice', scopedSlots: { customRender: 'exTaxPrice' } },
        { title: '超欠供含税单价', width: 150, dataIndex: 'inTaxPrice', scopedSlots: { customRender: 'inTaxPrice' } },
        { title: '超欠供不含税金额', width: 150, dataIndex: 'exTaxAmount', scopedSlots: { customRender: 'exTaxAmount' } },
        { title: '超欠供含税金额', width: 150, dataIndex: 'inTaxAmount', scopedSlots: { customRender: 'inTaxAmount' } },
        { title: '备注', width: 250, dataIndex: 'remark', scopedSlots: { customRender: 'remark' } }
      ],
      downloadApi: Api.downMaterialAnalysisExcel,
      delFunc: Api.deleteByDetails,
      loadData: params => Api.findListByDetails({}, Object.assign(params, { query: { sceneCostAnalysisId: this.id } }))
    }
  },
  methods: {
    async importFunc(e) {
      // this.$console(e)
      let newTable = []
      let checkRes = true
      e.map(row => {
        let temp = {}
        for (const rowKey in row) {
          let column = this.columns.find(columnRow => columnRow.title === rowKey)
          if (column) {
            let dataIndex = column.dataIndex
            temp[dataIndex] = row[rowKey]
            if (checkRes && rowKey === '期初累计进场数量' && typeof row[rowKey] !== 'number') checkRes = false
            if (checkRes && rowKey === '当月进场数量' && typeof row[rowKey] !== 'number') checkRes = false
            if (checkRes && rowKey === '累计总进场量' && typeof row[rowKey] !== 'number') checkRes = false
            if (checkRes && rowKey === '期初累计消耗数量' && typeof row[rowKey] !== 'number') checkRes = false
            if (checkRes && rowKey === '当月消耗数量' && typeof row[rowKey] !== 'number') checkRes = false
            if (checkRes && rowKey === '累计消耗数量' && typeof row[rowKey] !== 'number') checkRes = false
            if (checkRes && rowKey === '当月库存数量' && typeof row[rowKey] !== 'number') checkRes = false
            if (checkRes && rowKey === '材料超欠供数量' && typeof row[rowKey] !== 'number') checkRes = false
            if (checkRes && rowKey === '税率' && typeof row[rowKey] !== 'number') checkRes = false
            if (checkRes && rowKey === '超欠供不含税单价' && typeof row[rowKey] !== 'number') checkRes = false
            if (checkRes && rowKey === '超欠供含税单价' && typeof row[rowKey] !== 'number') checkRes = false
            if (checkRes && rowKey === '超欠供不含税金额' && typeof row[rowKey] !== 'number') checkRes = false
            if (checkRes && rowKey === '超欠供含税金额' && typeof row[rowKey] !== 'number') checkRes = false
          }
        }
        temp.sceneCostAnalysisId = this.id
        newTable.push(temp)
      })
      if (!checkRes) {
        return this.$noticeWarning('数据格式错误！')
      }
      this.loading = true
      let res = await Api.createByDetailsList({},newTable)
      this.loading = false
      if (res.code === this.SUCCESS_CODE) {
        if (res.message === 'success') {
          this.$noticeSuccess('导入成功！')
          this.$refs.table.getData(null, true)
        } else {
          this.$notification.open({ message: '提示', duration: null, description: () => <pre>{res.message}</pre> })
        }
      }
    },
    async openDialog(downloadApi) {
      let allData = []
      if (this.$refs.table.totalSize !== 0) {
        this.loadingAdd = true
        let res = await Api.findListByDetails({},{
          pageSize: this.$refs.table.totalSize,
          pageNo: 1,
          query: { sceneCostAnalysisId: this.id }
        })
        this.loadingAdd = false
        if (res.code === this.SUCCESS_CODE) {
          allData = res.data
        }
      }
      if (downloadApi) {
        let fileName = '标准模板下载.xlsx'
        this.$refs.detailDialog.download(allData, downloadApi)
      } else {
        this.$refs.detailDialog.open(allData)
      }
    },
    async createList(selectRows) {
      let params = []
      selectRows.map(selectRow => {
        params.push({
          materialName: selectRow.materialName,
          materialCode: selectRow.materialCode,
          materialModel: selectRow.specificationModel,
          materialUnit: selectRow.unit,
          materialId: selectRow.id,
          sceneCostAnalysisId: this.id
        })
      })
      this.loading = true
      let res = await Api.createByDetailsList({},params)
      this.loading = false
      if (res.code === 200) {
        this.$refs.table.refresh()
      }
    },
    save(target) {
      target.baseId = this.id
      try {
        if (
          target.allinNumbers !== null && target.alloutNumbers !== null && target.monthstocNumbers !== null
        ) {
          target.mcNumbers =
            target.allinNumbers -
            target.alloutNumbers -
            target.monthstocNumbers
          target.mcNumbers = target.mcNumbers.toFixed(2)
        } else {
          target.mcNumbers = null
        }
      } catch (e) {
      }
      Api.editByByDetail({},target).then(res => {
        if (res.code !== 200) this.$noticeWarning(res.message)
      })
    }

  }
}
</script>
